package cn.edu.hpu.jie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import cn.edu.hpu.jie.entity.VoteInfo;
import cn.edu.hpu.jie.util.RowMapping;
import cn.edu.hpu.jie.util.VoteDB;

public class VoteDao {
	private VoteDB<VoteInfo> db = new VoteDB<VoteInfo>();
	private class VoteInfoMapping implements RowMapping<VoteInfo>{

		public VoteInfo getMapping(ResultSet rs) throws SQLException {
			VoteInfo vi = new VoteInfo();
			vi.setId(rs.getInt("id"));
			vi.setIpaddress(rs.getString("ipaddress"));
			vi.setNo(rs.getString("no"));
			vi.setTime(rs.getString("time"));
			return null;
		}
	}
	
	public int insertVoteInfo(VoteInfo vi) {
		String sql = "INSERT INTO t_voteinfo(ipaddress, no, time) VALUES (?, ?, ?)";
		return db.getInsertPrimaryKey(sql, vi.getIpaddress(), vi.getNo(), vi.getTime());
	}
	
	public List<String> getNoAll() {
		String sql = "SELECT no FROM t_voteinfo";
		return db.getNoAll(sql);
	}

	public int insertVote(int key, String[] voteArray) {
		Object[] array = new Object[voteArray.length * 2];
		array[0] = key;
		array[1] = Integer.parseInt(voteArray[0]);
		
		StringBuilder sb = new StringBuilder("INSERT INTO t_vote (candidateid, voteinfo_id) VALUES(?, ?)");
		
		for(int i = 1; i < voteArray.length; i++) {
			sb.append(",(?, ?)");
			array[i * 2] = key;
			array[i * 2 + 1] = Integer.parseInt(voteArray[i]);
		}
		return db.updateData(sb.toString(), array);
	}
}
